function [WM,order]=RUMoment(D,order,j)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% File:               RUMoment.m
%
% Author:             Tasos Kalandrakis
%
% Description:        Evaluates moment function m^R for moment
%                     inequalities (M_R); and moment function m^U for
%                     moment inequalities (M_U), data D, p=order, and r=j.                      
%                     For test \pi=p, \bar{r}=j under (D), (C), (E), (R).
%
% Created:            May - 17 - 2017
%
% Last Modified:      May - 2 - 2018
%
% Language:           MATLAB
%
% Related Reference: Tasos Kalandrakis. "One-dimensional scaling without 
%                    without apologies," forthcoming, Journal of
%                    Politics
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin<2
    P=size(D,2);
    order=1:P;
    j=1;
end
D=D(:,order);
[N,P]=size(D);
Triplets=P*(P-1)*(P-2)/6;
WM=zeros(N,Triplets+P-1);

col=1;
for r1=1:P-2
    for r2=r1+1:P-1
        for r3=r2+1:P
            WM(:,col)=(D(:,r1)<min([D(:,r2) D(:,r3)],[],2))+...
                      (D(:,r3)<min([D(:,r1) D(:,r2)],[],2))-...
                      2*(D(:,r2)<min([D(:,r1) D(:,r3)],[],2));
            col=col+1;
        end
    end
end
if j>1
    for r=2:j
        WM(:,col)=D(:,r)-D(:,r-1);
        col=col+1;
    end
end
if j<P
    for r=j:P-1
        WM(:,col)=D(:,r)-D(:,r+1);
        col=col+1;
    end
end

end